package org.jianfa.rpc.consumer.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.jianfa.learn.common.request.RpcRequest;
import org.jianfa.learn.common.serializer.JSONSerializer;
import org.jianfa.learn.common.service.IUserService;
import org.jianfa.learn.common.zookeeper.ZookeeperRegistryCenter;
import org.jianfa.rpc.consumer.encoder.RpcEncoder;
import org.jianfa.rpc.consumer.handler.UserClientHandler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 消费者
 */
public class RpcConsumer {

    //1.创建一个线程池对象  -- 它要处理我们自定义事件
    private static ExecutorService executorService =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //2.声明一个自定义事件处理器  UserClientHandler
    private static Map<String, UserClientHandler> userClientHandlerMap = new ConcurrentHashMap<>();

    private static Map<String, EventLoopGroup> eventLoopGroupMap = new ConcurrentHashMap<>();

    private static Map<String, IUserService> userServiceMap = new ConcurrentHashMap<>();

    //3.编写方法,初始化客户端  ( 创建连接池  bootStrap  设置bootstrap  连接服务器)
    public static void init() throws Exception {

        //
        ZookeeperRegistryCenter zookeeperRegistryCenter = new ZookeeperRegistryCenter();
        zookeeperRegistryCenter.init();

        String serversPath = "/servers";
        //获取子节点列表
        //List<String> serversChildren = zookeeperRegistryCenter.getChildren(serversPath);
        //for (String host : serversChildren) {
        //    System.out.println(String.format("客户端搜索到服务器%s在线。", host));
        //    createUserClientHandler(host);
        //}

        //注册监听器
        zookeeperRegistryCenter.addCacheData(serversPath);
        PathChildrenCache pathChildrenCache = zookeeperRegistryCenter.getPathChildrenCache(serversPath);
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                switch (event.getType()) {
                    case CHILD_ADDED:
                        String childAddedPath = event.getData().getPath();
                        String childAddedData = new String(event.getData().getData());

                        String addHost = childAddedPath.substring(childAddedPath.lastIndexOf("/") + 1);
                        System.out.println(String.format("↗↗↗↗客户端监听到服务器%s上线。", addHost));
                        createUserClientHandler(addHost);
                        break;
                    case CHILD_REMOVED:
                        String childRemovedPath = event.getData().getPath();
                        String childRemovedData = new String(event.getData().getData());

                        String removeHost = childRemovedPath.substring(childRemovedPath.lastIndexOf("/") + 1);
                        System.out.println(String.format("↙↙↙↙客户端监听到服务器%s下线。", removeHost));
                        destroyUserClientHandler(removeHost);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    public static void createUserClientHandler(String host) throws Exception{
        //1) 初始化UserClientHandler
        UserClientHandler userClientHandler  = new UserClientHandler();
        //2)创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        //3)创建客户端的引导对象
        Bootstrap bootstrap =  new Bootstrap();
        //4)配置启动引导对象
        bootstrap.group(group)
                //设置通道为NIO
                .channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY,true)
                //监听channel 并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取ChannelPipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //设置编码
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        //添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });

        //5)连接服务端
        String inetHost = host.substring(0, host.indexOf(":"));
        int inetPort = Integer.valueOf(host.substring(host.indexOf(":") + 1));
        bootstrap.connect(inetHost,inetPort).sync();
        System.out.println(String.format("↗↗↗↗客户端连接服务器%s成功。", host));

        userClientHandlerMap.put(host, userClientHandler);
        eventLoopGroupMap.put(host, group);

        Object proxy = createProxy(host, IUserService.class);
        userServiceMap.put(host, (IUserService)proxy);
    }

    public static void destroyUserClientHandler(String host) throws Exception{
        userServiceMap.remove(host);
        userClientHandlerMap.remove(host);
        EventLoopGroup group = eventLoopGroupMap.remove(host);
        group.shutdownGracefully();
        System.out.println(String.format("↙↙↙↙客户端删除服务器%s成功。", host));
    }

    public static Map<String, IUserService> getProxys() {
        return userServiceMap;
    }

    //4.编写一个方法,使用JDK的动态代理创建对象
    // serviceClass 接口类型,根据哪个接口生成子类代理对象;   providerParam :  "UserService#sayHello#"
    public static Object createProxy(final String host, final Class<?> serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                        //1)初始化客户端cliet
                        if(userClientHandlerMap.isEmpty()){

                        }

                        //2)给UserClientHandler 设置param参数
                        //
                        RpcRequest rpcRequest = new RpcRequest();

                        String className  = serviceClass.getCanonicalName(); //类名
                        String methodName = method.getName(); //方法名
                        Class<?>[] parameterTypes = method.getParameterTypes(); //参数类型

                        rpcRequest.setRequestId("");
                        rpcRequest.setClassName(className);
                        rpcRequest.setMethodName(methodName);
                        rpcRequest.setParameterTypes(parameterTypes);
                        rpcRequest.setParameters(objects);

                        UserClientHandler userClientHandler = userClientHandlerMap.get(host);
                        userClientHandler.setRpcRequest(rpcRequest);

                        //3).使用线程池,开启一个线程处理处理call() 写操作,并返回结果
                        Object result = executorService.submit(userClientHandler).get();

                        //4)return 结果
                        return result;
                    }
                });
    }

}
